<template lang="pug">
q-input(v-model="value" @update:model-value="changeValue" @input="modifyNumber" ref="input" type="number" :hint="`支持${digNum}位小数`")
</template>

<script setup>
import {computed, onMounted, ref} from "vue";

const props = defineProps({
  modelValue: {
    type: Number,
    default: null
  },
  digNum: {
    type: Number,
    default: 0
  },
  min: {
    type: Number,
    default: null
  },
  max: {
    type: Number,
    default: null
  },
})

const emit = defineEmits(['update:modelValue'])

const input = ref(null)
const changeValue = (val) => {
  console.log(val)
}


const value = computed({
  get: () => {
    // if (!props.modelValue) emit('update:modelValue', 0)
    return props.modelValue
  },
  set: (val) => {
    const num = modifyNumber(val)
    if (num) emit('update:modelValue', num)
  }
})

const modifyNumber = (num) => {
  if (!num) return num
  let flag = false
  // 转换为字符串
  let str = num.toString()
  // 如果有小数点
  if (str.indexOf('.') > -1) {
    // 判断小数点后的位数是否为dig_num
    let arr = str.split('.')
    // 如果小数点后的位数大于dig_num， 则截取dig_num位
    if (arr[1].length > props.digNum) {
      str = arr[0] + '.' + arr[1].slice(0, props.digNum)
      flag = true
    }
    num = Number(str)
  }
  if (props.min !== null && num < props.min) {
    num = props.min
    flag = true
  }
  if (props.max !== null && num > props.max) {
    num = props.max
    flag = true
  }
  if (flag) {
    input.value.blur()
    input.value.focus()
  }
  return num
}


onMounted(() => {
})

</script>

<style scoped>

</style>